const FriendRequestDao = require('../dao/friendRequestDao');
const FriendDao = require('../dao/friendDao');
const UserDao = require('../dao/userDao');
const BlackListDao = require('../dao/blackListDao');
const UserRightsDao = require('../dao/userRightsDao');
exports.refresh = function (params) {
    return new Promise(function (resolve, reject) {
        params.CreatedAt = new Date();
        FriendRequestDao.queryFriendRequest(masterPool,params)
            .then(function (result) {
                let options = {openid:result[0].MeOpenId};
                return UserDao.queryUser(masterPool, options)
                    .then(function (result) {
                        let userInfo = result[0];
                        if (userInfo.FreeAddNum == 1)
                            return UserDao.updateUser(masterPool, {openid: options.openid, FreeAddNum: 0});
                        if (userInfo.ShareAddNum > 0)
                            return UserDao.updateUser(masterPool, {
                                openid: options.openid,
                                ShareAddNum: userInfo.ShareAddNum - 1
                            });
                        if (userInfo.PaidAddNum > 0)
                            return UserDao.updateUser(masterPool, {
                                openid: options.openid,
                                PaidAddNum: userInfo.PaidAddNum - 1
                            });
                        throw {code: 203};
                    })
            })
            .then(function () {
                return FriendRequestDao.updateFriendRequest(masterPool, params);
            })
            .then(function() {
                weChatApi.sendText(params.TaOpenId, "请到 <a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxecae704ec4ae66da&redirect_uri=http%3A%2F%2Fhl.ileadtek.com%2Fwebroot%2Ffriends.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'>好友列表</a> 确认新好友", function (err, result) {
                    console.log("=refreshFriend sendText err=", err);
                    console.log("=refreshFriend sendText result=", result);
                });
                resolve('操作成功')
            }, reject);
    });
};
exports.create = function (params) {
    params.MeOpenId = params.openid;
    params.StatusCode = "WAIT";
    return new Promise(function (resolve, reject) {
        let userInfo = "";
        mysqlHelper.getConn()
            .then(function (conn) {
                UserRightsDao.queryRights(conn, params)
                    .then(function (result) {
                        if (result.length > 0 && result[0].RightsAddFriend == 'T')
                            return conn.openTransaction();
                        throw {code: 402};
                    })
                    .then(function () {
                        return BlackListDao.isBlack(conn, {openid: params.openid, BlackOpenId: params.TaOpenId});
                    })
                    .then(function (result) {
                        if (result.length > 0)
                            return BlackListDao.deleteBlack(conn, result[0]);
                    })
                    .then(function () {
                        return FriendDao.isFriend(conn, {openid: params.openid, FriendOpenId: params.TaOpenId})
                    })
                    .then(function (result) {
                        if (result.length > 0)
                            throw {code: 204};
                        return FriendRequestDao.isExistFriendRequest(conn, params.openid, params.TaOpenId);
                    })
                    .then(function (result) {
                        if (result.length > 0)
                            throw {code: 202};
                        return FriendRequestDao.isExistFriendRequest(conn, params.TaOpenId, params.openid)
                    })
                    .then(function (result) {
                        if (result.length > 0)
                            return accept(conn, result);
                        return UserDao.queryUser(conn, params)
                            .then(function (result) {
                                userInfo = result[0];
                                if (userInfo.FreeAddNum == 1)
                                    return UserDao.updateUser(conn, {openid: params.openid, FreeAddNum: 0});
                                if (userInfo.ShareAddNum > 0)
                                    return UserDao.updateUser(conn, {
                                        openid: params.openid,
                                        ShareAddNum: userInfo.ShareAddNum - 1
                                    });
                                if (userInfo.PaidAddNum > 0)
                                    return UserDao.updateUser(conn, {
                                        openid: params.openid,
                                        PaidAddNum: userInfo.PaidAddNum - 1
                                    });
                                throw {code: 203};
                            })
                            .then(function () {
                                return FriendRequestDao.createFriendRequest(conn, params);
                            })
                    })
                    .then(function () {
                        return conn.commitTransaction();
                    }, function (err) {
                        conn.rollbackTransaction();
                        throw err;
                    })
                    .then(function () {
                        conn.releaseConn();
                        resolve("发送成功");
                        weChatApi.sendText(params.TaOpenId, "请到 <a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxecae704ec4ae66da&redirect_uri=http%3A%2F%2Fhl.ileadtek.com%2Fwebroot%2Ffriends.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'>好友列表</a> 确认新好友", function (err, result) {
                            console.log("=addFriend sendText err=", err);
                            console.log("=addFriend sendText result=", result);
                        });
                    }, function (err) {
                        console.log(err);
                        conn.releaseConn();
                        reject(err)
                    });
            });
        function accept(conn, params) {
            console.log(params);
            return new Promise(function (resolve, reject) {
                let createdAt = new Date();
                FriendDao.batchInsertFriend(conn, [
                    [params[0].MeOpenId, params[0].TaOpenId, createdAt],
                    [params[0].TaOpenId, params[0].MeOpenId, createdAt]
                ])
                    .then(function () {
                        return FriendRequestDao.deleteFriendRequest(conn, params[0]);
                    })
                    .then(resolve, reject)
            });
        }
    });
};
exports.list = function (params) {
    return new Promise(function (resolve, reject) {
        if (params.ListType == "receive") {
            params.TaOpenId = params.openid;
            UserDao.queryUserDetail(masterPool, params)
                .then(function (result) {
                    return FriendRequestDao.selectFriendRequestToMe(masterPool, {
                        params: params,
                        selfInfo: result[0]
                    }, true);
                })
                .then(resolve, reject);
        } else {
            params.MeOpenId = params.openid;
            UserDao.queryUserDetail(masterPool, params)
                .then(function (result) {
                    return FriendRequestDao.selectFriendRequestToTa(masterPool, {
                        params: params,
                        selfInfo: result[0]
                    }, true);
                })
                .then(resolve, reject);
        }
    })
};
exports.delete = function (params) {
    return new Promise(function (resolve, reject) {
        FriendRequestDao.deleteFriendRequest(masterPool, params)
            .then(resolve("删除成功"), reject);
    });
};
exports.accept = function (params) {
    return new Promise(function (resolve, reject) {
        let MeOpenId = "";
        mysqlHelper.getConn()
            .then(function (conn) {
                conn.openTransaction()
                    .then(function () {
                        return FriendRequestDao.queryFriendRequest(conn, params);
                    })
                    .then(function (result) {
                        let createdAt = new Date();
                        MeOpenId = result[0].MeOpenId;
                        return FriendDao.batchInsertFriend(conn, [
                            [result[0].MeOpenId, result[0].TaOpenId, createdAt],
                            [result[0].TaOpenId, result[0].MeOpenId, createdAt]
                        ]);
                    })
                    .then(function () {
                        return FriendRequestDao.deleteFriendRequest(conn, params);
                    })
                    .then(function (result) {
                        return conn.commitTransaction();
                    }, function (err) {
                        conn.rollbackTransaction();
                        throw err;
                    })
                    .then(function () {
                        conn.releaseConn();
                        resolve("操作成功");
                        weChatApi.sendText(MeOpenId, "请到 <a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxecae704ec4ae66da&redirect_uri=http%3A%2F%2Fhl.ileadtek.com%2Fwebroot%2Fmessage_friends.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'>好友列表</a> 确认新好友", function (err, result) {
                            console.log("=acceptFriend sendText err=", err);
                            console.log("=acceptFriend sendText result=", result);
                        });
                    }, function (err) {
                        console.log(err);
                        conn.releaseConn();
                        reject(err)
                    });
            })
    });
};
